printArrayCsv
Arrays Sandbox PanosP Revised

Printing an Array with Commas

Problem
=======

Print all array elements as a comma separated list.
We can print a number indexed array in an ordered
fashion, or print all elements of an associative
array in a random order.

Solution
========

 function csvArray(arr, from, to,		i, first) {
 	if (from != "") {
 		printf arr[from]
 		for (i = from + 1; i <= to; i++)
 			printf "," arr[i]
 	}
 	else {
 		first = 1
 		for (i in arr) {
 			if (first) {
 				printf arr[i]
 				first = 0
 			}
 			else
 				printf "," arr[i]
 		}
 	}
 	print ""
 }

The above function takes at most three arguments.
The first argument is, of course, the array to print.
That's a mandatory argument.
The other two arguments are optional, either none
or both of the `from` and `to` arguments must
be supplied; if supplied, then both `from`
and `to` must be numbers that specify a range of indices
of the corresponding elements of the array to print
as a comma separated list.
If the `from` and `to` arguments are missing,
then all of the array elements will be printed
(in random order) as a comma separated list.

Discussion
==========

In case of an empty array the above function may print
just a newline an nothing else.
In case of ordered print (specified `from` and `to`
arguments), if some of the indices are missing, then:

+ missing elements will be printed as empty strings.
+ missing elements will be inserted in the array, because
just the reference of an element using a specific index
will cause the insertion of the corresponding element
if it doesn't exist already (a well known sideffect of
arrays in gawk, useful most of the times).

Author
======

Panos Papadopoulos

